import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { setToken, getToken } from '@/utils/auth'
const qs = require('qs')

// 请求状态设置
let ResultData = {
  SUCCESS: {
    msg: '成功',
    status: '00000'
  },
  LOGIN_SUCCESS: {
    msg: '登录成功',
    status: '00001'
  },
  FAILED: {
    msg: '系统执行出错',
    status: 'B0001'
  },
  PERMISSION_DENIED: {
    msg: '无权限',
    status: 'B0002'
  },
  LOGIN_FAILED: {
    msg: '登录失败',
    status: 'B0003'
  },
  AUTH_FAILED: {
    msg: '登录信息验证失败',
    status: 'B0004'
  }
}

// axios 全局配置
axios.defaults.paramsSerializer = function(params) {
  return qs.stringify(params, { arrayFormat: 'repeat', allowDots: true })
}

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.status === ResultData.SUCCESS.status) {
      return res
    } else if (res.status === ResultData.LOGIN_SUCCESS.status) {
      // 登录成功, 保存token
      let token = response.headers['authorization']
      setToken(token)
      res.token = token
      return res
    } else {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 登录信息验证失败, 需要重新登录
      if (res.status === ResultData.AUTH_FAILED.status) {
        // to re-login
        MessageBox.confirm('登录信息失效，您可以保持在这个页面，或重新登录。', '提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
